# _*_ utf-8 _*_
# 武将管理类
# 在管理类中需要完成一个武将的排序 功能：按照武将的胜利场次进行排序
from os import environ
# 取消pygame默认的加载版本信息
from lesson5.three_kingdoms_generals.Hero import Hero
import random
import time

environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"
# 初始化得英雄列表
hero_lst = []
menu = """            1、招揽武将
            2、武将重修
            3、武将充值
            4、沙场秋点兵(查询武将)
            5、武将演武场(随机大乱斗，最后根据胜利场次进行排序并显示)"""


def initial_hero():
    hero1 = Hero(hero_id=1, hero_name="曹操", hero_attack=87, hero_INT=96, hero_hp=83, hero_mp=44)
    hero2 = Hero(hero_id=2, hero_name="典韦", hero_attack=98, hero_INT=45, hero_hp=84, hero_mp=36)
    hero3 = Hero(hero_id=3, hero_name="关羽", hero_attack=99, hero_INT=84, hero_hp=84, hero_mp=42)
    hero4 = Hero(hero_id=4, hero_name="诸葛亮", hero_attack=68, hero_INT=80, hero_hp=80, hero_mp=45)
    hero5 = Hero(hero_id=5, hero_name="黄盖", hero_attack=88, hero_INT=83, hero_hp=83, hero_mp=40)
    hero6 = Hero(hero_id=6, hero_name="周瑜", hero_attack=78, hero_INT=81, hero_hp=81, hero_mp=44)
    hero7 = Hero(hero_id=7, hero_name="吕布", hero_attack=100, hero_INT=85, hero_hp=85, hero_mp=36)
    hero8 = Hero(hero_id=8, hero_name="貂蝉", hero_attack=52, hero_INT=77, hero_hp=77, hero_mp=41)
    hero_lst.append(hero1)
    hero_lst.append(hero2)
    hero_lst.append(hero3)
    hero_lst.append(hero4)
    hero_lst.append(hero5)
    hero_lst.append(hero6)
    hero_lst.append(hero7)
    hero_lst.append(hero8)


def print_hero_info():
    sf_title = "{:6}{:6}\t{:5}{:5}{:5}{:5}{:6}"
    print(sf_title.format("武将编号", "武将名称", "武力值", "智力值", "体力值", "魔法值", "胜利场次"))
    for hero in hero_lst:
        print(hero)


class HeroManage:
    """
        英雄得管理类
    """

    def __init__(self, app_name):
        self.__App_name__ = app_name

    def main_enter(self):
        print(("欢迎使用<" + self.__App_name__ + ">").center(50, "-"))
        choice = "y"
        while "n" != choice and "N" != choice:
            print(menu)
            choice = input("请选择(n/N:退出):"
                           "")
            if "1" == choice:
                self.enlist_hero()
            elif "2" == choice:
                self.del_hero()
            elif "3" == choice:
                self.recharge()
            elif "4" == choice:
                self.query_hero()
            elif "5" == choice:
                self.group_battle()
            else:
                print("暂时不支持其他的功能，待新增".center(50, "#"))
        self.print_quit_wel()

    def print_quit_wel(self):
        print("-" * 58)
        print(("欢迎您使用<" + self.__App_name__ + ">,期待您的下次使用").center(45, "-"))

    def enlist_hero(self):
        """
        招募武将，武将类型有：武将（武力值高）、军师（智力值高）
        :return:
        1、招揽武将(增加武将)".center(50, "#")
        """
        print("\t\t主菜单 >> 招揽武将(增加武将)")
        hero = Hero(len(hero_lst) + 1, "默认武将姓名")
        hero.set_hero_name(input("\t\t请输入武将的名称:"))
        hero_type = input("\t\t选择武将的类型 (1-武将 2-军师):")
        # 验证输入的是否是一个数字
        while ord(hero_type[0]) < ord("0") or ord("9") < ord(hero_type[0]):
            hero_type = input("\t\t选择武将的类型 (1-武将 2-军师):")
        hero_type = int(hero_type[0])
        if hero_type != 1:  # 如果是军师，武力值要低一些，智力值高一些
            hero.set_hero_type(["武将", "军师"][hero_type - 1])
            hero.set_hero_group(hero.hero_group_lst[random.randint(0, len(hero.hero_group_lst) - 1)])
            hero.set_hero_INT(random.randint(85, 100))
            hero.set_hero_attack(random.randint(60, 85))
            hero.set_hero_hp(random.randint(60, 80))
            hero.set_hero_mp(random.randint(70, 90))
        else:
            hero.set_hero_type(["武将", "军师"][hero_type - 1])
            hero.set_hero_group(hero.hero_group_lst[random.randint(0, len(hero.hero_group_lst) - 1)])
            hero.set_hero_INT(random.randint(70, 90))
            hero.set_hero_attack(random.randint(85, 95))
            hero.set_hero_hp(random.randint(80, 100))
            hero.set_hero_mp(random.randint(65, 80))
        hero_lst.append(hero)
        # 打印招募的武将信息
        self.print_newest_hero_info()

    def del_hero(self):
        print("2、武将重修(删除武将)".center(50, "#"))
        choice_id = input("请选择要删除的武将编号：")
        while ord("0") > ord(choice_id) or ord(str(hero_lst[len(hero_lst) - 1].get_hero_id())) < ord(choice_id):
            choice_id = input("请选择要删除的武将编号 (n/N退出):")
            if choice_id == "n" or choice_id == "N":
                return
        choice_id = int(choice_id)
        del_hero = None
        for hero in hero_lst:
            if hero.get_hero_id() == choice_id:
                del_hero = hero
                break
        self.print_del_hero_info_by_hero(del_hero, "要删除武将信息")
        choice = input("是否进行删除(y/Y 确定) :")
        if "y" == choice or "Y" == choice:
            hero_lst.remove(del_hero)
            print("删除武将成功".center(50, "#"))

    def recharge(self):
        print("3、武将充值(修改武将)".center(50, "#"))
        choice_id = input("请选择要进行充值的武将编号：")
        while ord("0") > ord(choice_id) or ord(str(hero_lst[len(hero_lst) - 1].get_hero_id())) < ord(choice_id):
            choice_id = input("请选择要进行充值的武将编号 (n/N退出):")
            if choice_id == "n" or choice_id == "N":
                return
        choice_id = int(choice_id)
        recharge_hero = None
        for hero in hero_lst:
            if hero.get_hero_id() == choice_id:
                recharge_hero = hero
                break
        # 对查找到的英雄进行充值
        recharge = input("\t\t请输入要充值的金额:")
        # 充值是对武将的属性进行叠加，武力值，智力值，hp，mp
        random_max = self.produce_random_max_value(recharge)
        recharge_hero.set_hero_hp(recharge_hero.get_hero_hp() + random.randint(0, random_max))
        recharge_hero.set_hero_mp(recharge_hero.get_hero_mp() + random.randint(0, random_max))
        recharge_hero.set_hero_attack(recharge_hero.get_hero_attack() + random.randint(0, random_max))
        recharge_hero.set_hero_INT(recharge_hero.get_hero_INT() + random.randint(0, random_max))
        # 打印充值成功的英雄信息
        self.print_del_hero_info_by_hero(recharge_hero, "充值后武将的信息")

    def query_hero(self):
        print("4、沙场秋点兵(查询武将)".center(50, "#"))
        # 查询全部武将，按照武将名称进行查找
        choice = input("1-查询全部英雄信息 2-按名称查找武将 请选择:")
        while ord("0") > ord(choice[0]) or ord("2") < ord(choice[0]):
            choice = input("1-查询全部英雄信息 2-按名称查找武将 请选择(n/N 退出):")
            if choice == "N" or choice == "n":
                return
        choice = int(choice[0])
        if choice == 1:
            print("全部武将信息".center(50, "#"))
            print_hero_info()
            print("-" * 58)
        else:
            searched_hero = None
            search_name = input("请输入要查询武将的名称：")
            for hero in hero_lst:
                if search_name == hero.get_hero_name():
                    searched_hero = hero
                    break
            if searched_hero is not None:
                self.print_del_hero_info_by_hero(searched_hero, "查找到的英雄信息")
            else:
                print("您输入要查找的英雄不存在，请重试".center(50, "*"))

    def group_battle(self):
        print("\t主菜单 >> 武将演武场(随机大乱斗，最后根据胜利场次进行排序并显示)".center(50, "#"))
        # 大乱斗，连续对战10场，以胜利场数来进行排序显示
        for i in range(5):
            battle_lst = self.random_two_hero()
            hero1, hero2 = battle_lst[0], battle_lst[1]
            while hero1.get_hero_hp() > 0 and hero2.get_hero_hp() > 0:
                self.fight_print_info(hero1, hero2)
            if hero1.get_hero_hp() == hero2.get_hero_hp():
                # 平局，不进行任何操作
                pass
                # hero1.set_WINS(hero1.get_WINS() + 0)
                # hero2.set_WINS(hero2.get_WINS() + 0)
            elif hero1.get_hero_hp() > 0 >= hero2.get_hero_hp():
                # hero1 胜利
                hero1.set_WINS(hero1.get_WINS() + 1)
            else:
                hero2.set_WINS(hero2.get_WINS() + 1)
        print()
        print("乱斗结束".center(50, "#"))
        # 对大乱斗的结果进行打印，按照胜利的场次进行排序
        self.sort_hero_lst_and_print()
        print("-"*58)

    def sort_hero_lst_and_print(self):
        lst_sorted = []
        lst_sorted.extend(hero_lst)
        # 使用冒泡排序根据英雄的胜利场次进行排序
        for i in range(len(lst_sorted) - 1):
            max_index = i
            for j in range(i, len(lst_sorted)):
                if lst_sorted[j].get_WINS() > lst_sorted[max_index].get_WINS():
                    max_index = j
            lst_sorted[i], lst_sorted[max_index] = lst_sorted[max_index], lst_sorted[i]
        sf_title = "{:6}{:6}\t{:5}{:5}{:5}{:5}{:6}"
        print(sf_title.format("武将编号", "武将名称", "武力值", "智力值", "体力值", "魔法值", "胜利场次"))
        for hero in lst_sorted:
            print(hero)

    def fight_print_info(self, hero1, hero2):
        """
            为每个英雄添加技能，根据不同的攻击力添加技能
        :param hero1:
        :param hero2:
        :return:
        """
        fight_info = "\t\t{}打出了一记<{}>{}掉了{}两血, {}的当前血量为:{}"
        p1_power = hero1.get_attack_power(hero2)
        p2_power = hero2.get_attack_power(hero1)
        print("\r" + fight_info.format(hero1.get_hero_name(), "普攻", hero2.get_hero_name(), p1_power,
                                       hero2.get_hero_name(), hero2.get_hero_hp()), end="")
        hero1.attack(hero2, p1_power)
        time.sleep(0.1)
        hero2.attack(hero1, p2_power)
        print("\r" + fight_info.format(hero2.get_hero_name(), "普攻", hero1.get_hero_name(), p2_power,
                                       hero1.get_hero_name(), hero1.get_hero_hp()), end="")
        time.sleep(0.1)

    def random_two_hero(self):
        """
            如果两个人的血量都大于0，这中才是合适的随机英雄
        :return:
        """
        rand_hero_p1 = None
        rand_hero_p2 = None
        while True:
            rand_hero_p1 = hero_lst[random.randint(0, len(hero_lst) - 1)]
            rand_hero_p2 = hero_lst[random.randint(0, len(hero_lst) - 1)]
            if rand_hero_p1.get_hero_id() != rand_hero_p2.get_hero_id() and rand_hero_p1.get_hero_hp() > 0 \
                    and rand_hero_p2.get_hero_hp() > 0:
                break
        return [rand_hero_p1, rand_hero_p2]

    def print_newest_hero_info(self):
        print("新增武将信息".center(45, "-"))
        sf_title = "{:6}{:6}\t{:5}{:5}{:5}{:5}{:6}"
        print(sf_title.format("武将编号", "武将名称", "武力值", "智力值", "体力值", "魔法值", "胜利场次"))
        print("-" * 58)
        print(hero_lst[len(hero_lst) - 1])
        print("-" * 58)

    def print_del_hero_info_by_hero(self, hero, sf_title=""):
        print(sf_title.center(45, "-"))
        sf_title = "{:6}{:6}\t{:5}{:5}{:5}{:5}{:6}"
        print(sf_title.format("武将编号", "武将名称", "武力值", "智力值", "体力值", "魔法值", "胜利场次"))
        print("-" * 58)
        print(hero)
        print("-" * 58)

    def produce_random_max_value(self, recharge):
        """
        根据充值的金额，随机生成一个随机数字的最大值, 这里没有对输入的充值金额进行数字验证
        :param recharge:充值的金额
        :return:随机数
        """
        random_max = 0
        recharge = int(recharge)
        if recharge >= 1000:
            random_max = 15
        elif recharge >= 500:
            random_max = 10
        elif recharge >= 100:
            random_max = 7
        elif recharge >= 50:
            random_max = 5
        else:
            random_max = 3
        return random_max
